<?php

namespace App\Http\Controllers\Api;

use App\Helpers\Api\TtMiniTrait;
use App\Http\Controllers\BaseController;
use App\Jobs\ReadLogMigrate;
use App\Models\Animal;
use App\Models\Article;
use App\Models\Circle;
use App\Models\Share;
use App\Models\User;
use App\Models\UserExtend;
use App\Models\UserRead;
use App\Services\ReadStoreService;
use function EasyWeChat\Kernel\Support\get_client_ip;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use itbdw\Ip\IpLocation;

class AuthController extends BaseController
{
    use TtMiniTrait;

    public function fakeLogin(Request $request) {
        $input = $request->input();
        if (!empty($input['user_id'])) {
            $user = User::find($input['user_id']);
            if (!$token = \Auth::guard('api')->fromUser($user)) {
                return $this->failed('登录失败', 401);
            }
            return $this->respondWithToken($token, $user);
        }
    }

    public function login(Request $request)
    {
        $input = $request->input();
        \Log::info("weixin-login-param : " . var_export($input, true));
        $this->validate($request, [
            'code' => 'required',
            'encryptedData' => 'required',
            'iv' => 'required',
        ]);
        $app = $this->miniProgram();

        $ip = get_client_ip();
        if (env('APP_ENV') == 'production') {
            $arr = IpLocation::getLocation($ip);
            if (!empty($arr['area']) &&  $arr['area'] == '中国上海腾讯云') {
                \Log::error($ip . '-login-fail');
                return $this->failed('登录失败，请联系客服');
            }
            if ($ip == '106.4.249.217' || $ip == '1.31.112.182' || $ip == '59.152.38.213')
                return $this->failed('登录失败，请您联系客服');
        }

        $session = $app->auth->session($request->code);
        \Log::info("weixin-session : " . var_export($session, true));
        if (isset($session['errcode']) &&  $session['errcode'] > 0)
            return $this->failed($session['errmsg']);
        try {
            $total = 0;
            $userInfo = $app->encryptor->decryptData(
                $session['session_key'],
                $request->iv,
                $request->encryptedData
            );
            \Log::info("weixin-decrypt : " . var_export($userInfo, true));
        } catch (\Exception $e) {
            \Log::error($e->getMessage());
            return $this->failed('网络异常，请重新操作');
        }
        $fake_uid = $request->header('fake_uid');

        $cache_key = 'login_open_id' . $userInfo['openId'];
        if (Redis::setnx($cache_key, 1)) {
            Redis::expire($cache_key, 10);
            try {
                $user = User::where('openid', $userInfo['openId'])->orderBy('id', 'desc')->first();
                $arr_gender = [0 => '未知', '1' => '男', '2' => '女'];
                if (!$user) {
                    if (!$userInfo['avatarUrl'])
                        return $this->failed('登录失败，请您重试');

                    $channel_type = $input['channel_type'] ?? 0;
                    $channel_id = $input['channel_id'] ?? 0;
                    $user = new User();
                    $user->openid = $userInfo['openId'];
                    $user->nickname = $userInfo['nickName'];
                    $user->gender = $arr_gender[$userInfo['gender']] ?? 0;
                    $user->avatar_url = $userInfo['avatarUrl'];
                    $user->channel_type = $channel_type;
                    $user->channel_id = $input['channel_id'] ?? 0;
                    $user->sign = '这人很懒，什么都没有留下';
                    $user->ip = $ip;
                    $user->save();

                    $entity = null;
                    if ($channel_type == Share::TYPE_ARTICLE) {
                        $entity = Article::find($channel_id);
                    } elseif ($channel_type == Share::TYPE_CIRCLE) {
                        $entity = Circle::find($channel_id);
                    } elseif ($channel_type == Share::TYPE_ANIMAL) {
                        $entity = Animal::find($channel_id);
                    } elseif ($channel_type == Share::TYPE_ANIMAL_CANVAS) {
                        $entity = Animal::find($channel_id);
                    }
                    if ($entity) {
                        if ($channel_type == Share::TYPE_ANIMAL_CANVAS) {
                            $entity->share_canvas_reg_num += 1;
                        } else {
                            $entity->share_reg_num += 1;
                        }

                        $entity->save();
                    }

                    UserExtend::create([
                        'fake_uid' => $fake_uid,
                        'user_id' => $user->id
                    ]);
                } else {
                    if ($user->is_black)
                        return $this->failed('登录失败，加入黑名单');

                    $user->ip = $ip;
                    $user->save();

                    UserExtend::where('user_id', $user->id)->update([
                        'fake_uid' => $fake_uid
                    ]);
                }

                if (!$token = \Auth::guard('api')->fromUser($user)) {
                    return $this->failed('登录失败', 401);
                }


                $this->dispatch(new ReadLogMigrate($user->id, $fake_uid));
                Redis::del($cache_key);
                return $this->respondWithToken($token, $user);

            } catch (\Exception $e) {
                Redis::del($cache_key);
                return $this->failed($e->getMessage());
            }
        } else {
            return $this->failed("登录失败，请重试");
        }

    }
}
